package com.liao.badminton.handler.security;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.liao.badminton.code.util.WebUtil;
import com.liao.badminton.context.BaseContextHandler;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Iterator;

public class UserNamePasswordFilter extends UsernamePasswordAuthenticationFilter {
    private AuthenticationManager authenticationManager;
    private AuthenticationSuccessHandler successHandler;
    private AuthenticationFailureHandler failureHandler;

    public UserNamePasswordFilter(AuthenticationManager authenticationManager, AuthenticationSuccessHandler successHandler
            , AuthenticationFailureHandler failureHandler) {
        this.authenticationManager = authenticationManager;
        this.successHandler = successHandler;
        this.failureHandler = failureHandler;
    }


    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }
        BaseContextHandler.setIp(WebUtil.getClientIp(request));
        BaseContextHandler.setPort(WebUtil.getClientPort(request));
        String username = obtainUsername(request);
        String password = obtainPassword(request);
        JsonNode requestJson = null;
        if (username == null && (password == null)) {
            requestJson = getRequestJson(request);
        }
        if (username == null && requestJson != null) {
            username = requestJson.get("username").asText();
        } else if (username == null){
            username = "";
        }

        if (password == null && requestJson != null) {
            password = requestJson.get("password").asText();
        } else if (password == null){
            password = "";
        }

        username = username.trim();

        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                username, password);

        // Allow subclasses to set the "details" property
        setDetails(request, authRequest);

        return authenticationManager.authenticate(authRequest);
    }

    public static JsonNode getRequestJson(HttpServletRequest request) {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = null;
        try {
            // 1. 从HttpServletRequest对象中获取输入流，并读取请求正文。
            StringBuilder buffer = new StringBuilder();
            BufferedReader reader = request.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            String requestBody = buffer.toString();

            // 2. 使用JSON库（如Jackson、Gson等）将字符串解析为JsonNode或任何其他适合你的数据结构。
            // Jackson JSON库示例
            jsonNode = mapper.readTree(requestBody); // 解析为JsonNode对象

            // 3. 现在，你可以使用jsonNode对象来访问和操作JSON数据了。
//            String name = jsonNode.get("name").asText();
//            int age = jsonNode.get("age").asInt();
            // 遍历所有属性并打印它们的值：
//            Iterator<String> fieldNamesIter = jsonNode.fieldNames();
//            while (fieldNamesIter.hasNext()) {
//                String fieldName = fieldNamesIter.next();
//                JsonNode fieldValue = jsonNode.get(fieldName);
//                System.out.println(fieldName + ": " + fieldValue.asText());
//            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return jsonNode;
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request,
                                            HttpServletResponse response, FilterChain chain, Authentication authResult)
            throws IOException, ServletException {

        if (logger.isDebugEnabled()) {
            logger.debug("Authentication success. Updating SecurityContextHolder to contain: "
                    + authResult);
        }

        SecurityContextHolder.getContext().setAuthentication(authResult);

//        rememberMeServices.loginSuccess(request, response, authResult);

        // Fire event
        if (this.eventPublisher != null) {
            eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(
                    authResult, this.getClass()));
        }

        successHandler.onAuthenticationSuccess(request, response, authResult);
    }

    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request,
                                              HttpServletResponse response, AuthenticationException failed)
            throws IOException, ServletException {
        SecurityContextHolder.clearContext();

        if (logger.isDebugEnabled()) {
            logger.debug("Authentication request failed: " + failed.toString(), failed);
            logger.debug("Updated SecurityContextHolder to contain null Authentication");
            logger.debug("Delegating to authentication failure handler " + failureHandler);
        }
        failureHandler.onAuthenticationFailure(request, response, failed);
    }
}
